import { css } from "@emotion/react"
import { useCallback, useEffect, useMemo, useState } from "react"
import { motion } from "motion/react"
import styled from "@emotion/styled"
import { ButtonConfirm } from "./components/common"
import MarginTopBlock from "@/components/base/MarginTopBlock"
import { kycForm } from "@/forms"
import Constants from "@/constants/kyc"
import { createLogger } from "@/utils/logger"
import { CustomError } from "@/utils/error"
import KycPageSignals from "@/features_signal/kycPageSignals"
const logger = createLogger("StepKycSelectIdType")

const ButtonNext = styled(ButtonConfirm)`
    margin-top: auto;
`

export default function StepKycSelectIdType() {
    const form = kycForm.useFormContext()

    const idTypeValue = form.watch("id_type")

    const handleChange = useCallback(
        (value: Kyc.IdType) => {
            form.setValue("id_type", value)
        },
        [form],
    )

    const handleNext = useCallback(async () => {
        try {
            const ocrParams = await KycPageSignals.startOcr(idTypeValue)
            logger.info("StepKycSelectIdType", {
                ocrParams,
            })

            if (ocrParams.redirect_url) {
                location.href = ocrParams.redirect_url
            } else {
                form.setError("root", {
                    message: "Failed to start OCR",
                })
            }
        } catch (error) {
            if (error instanceof CustomError) {
                form.setError("root", {
                    message: error.message,
                })
            } else {
                form.setError("root", {
                    message: "Failed to start OCR",
                })
            }
        }
    }, [idTypeValue, form])

    useEffect(
        () => () => {
            form.setError("root", {
                message: "",
            })
        },
        // eslint-disable-next-line react-hooks/exhaustive-deps
        [],
    )

    return (
        <div
            css={css`
                flex: 1;
                display: flex;
                flex-direction: column;
                align-items: stretch;
                justify-content: flex-start;
                padding: 0 24rem;
                font-family: "Gilroy";
            `}
        >
            <div
                css={css`
                    font-weight: 600;
                    font-size: 24rem;
                    line-height: 36rem;
                    letter-spacing: 0%;
                    text-transform: capitalize;
                `}
            >
                ID Type
            </div>
            <div
                css={css`
                    margin-top: 8rem;
                    font-weight: 400;
                    font-size: 16rem;
                    line-height: 20rem;
                    letter-spacing: 0%;
                `}
            >
                Select the type of ID you want to verify
            </div>
            <MarginTopBlock top={32} />
            <IdTypeSelection
                value={idTypeValue}
                onChange={handleChange}
            />
            <MarginTopBlock top={24} />
            <ButtonNext
                disabled={!idTypeValue}
                onClick={handleNext}
            >
                Next
            </ButtonNext>
        </div>
    )
}

function IdTypeSelection(props: { value: Kyc.IdType; onChange: (value: Kyc.IdType) => void }) {
    const { value, onChange } = props

    const options = useMemo(() => {
        const _options = Constants.KycIdTypeOptions

        return _options
    }, [])

    return (
        <div
            css={css`
                display: flex;
                flex-direction: column;
                align-items: stretch;
                justify-content: space-between;
                gap: 8rem;
            `}
        >
            {options.map((option) => (
                <IdTypeOption
                    key={option.value}
                    option={option}
                    active={option.value === value}
                    onClick={() => onChange(option.value)}
                />
            ))}
        </div>
    )
}

function IdTypeOption(props: {
    //
    option: (typeof Constants.KycIdTypeOptions)[number]
    active: boolean
    onClick: () => void
}) {
    const { option, active, onClick } = props

    return (
        <motion.div
            css={css`
                display: flex;
                flex-direction: row;
                align-items: center;
                justify-content: space-between;
                gap: 8rem;
                height: 48rem;
                border-radius: 8rem;
                padding: 12rem 16rem;
                font-size: 16rem;
                line-height: 24rem;
                letter-spacing: 0%;
                text-align: center;
                vertical-align: middle;
                cursor: pointer;
                > * {
                    user-select: none;
                    pointer-events: none;
                }
            `}
            initial={{
                boxShadow: "0 0 0 1rem #d5d5d8 inset",
            }}
            animate={{
                boxShadow: `0 0 0 ${active ? "1.5rem" : "1rem"} ${active ? "#ff1f57" : "#d5d5d8"}
                        inset`,
            }}
            onClick={onClick}
        >
            <div>{option.label}</div>
            <motion.div
                css={css`
                    width: 18rem;
                    height: 18rem;
                    border-radius: 50%;
                `}
                initial={{
                    boxShadow: "0 0 0 1rem #838ca5 inset",
                }}
                animate={{
                    boxShadow: `0 0 0 ${active ? "2.5rem" : "1.5rem"} ${active ? "#ff1f57" : "#838ca5"}
                        inset`,
                }}
            />
        </motion.div>
    )
}
